import categoryApi from "@/api/category";
const state = {
  category1Id: "",
  category2Id: "",
  category3Id: "",
  category1List: [],
  category2List: [],
  category3List: [],
};
const mutations = {
  // 修改一级分类列表
  UPDATE_CATEGORY1LIST(state, category1List) {
    state.category1List = category1List;
  },
  // 修改二级分类列表
  UPDATE_CATEGORY2LIST(state, category1List) {
    state.category2List = category1List;
  },
  // 修改三级分类列表
  UPDATE_CATEGORY3LIST(state, category1List) {
    state.category3List = category1List;
  },
  // 修改一级分类id
  UPDATE_CATEGORY1ID(state, category1Id) {
    state.category1Id = category1Id;
  },
  // 修改二级分类id
  UPDATE_CATEGORY2ID(state, category2Id) {
    state.category2Id = category2Id;
  },
  // 修改三级分类id
  UPDATE_CATEGORY3ID(state, category3Id) {
    state.category3Id = category3Id;
  },
};
const actions = {
  // 获取一级分类列表
  async getCategory1List({ commit }) {
    try {
      const res = await categoryApi.getCategory1();
      if (res.code === 200) {
        commit("UPDATE_CATEGORY1LIST", res.data);
        return "ok";
      } else {
        return Promise.reject("fail");
      }
    } catch (error) {
      Message({
        message: "获取一级分类列表失败",
        type: "error",
      });
    }
  },
  //获取二级分类列表
  async getCategory2List({ commit }, category1Id) {
    commit("UPDATE_CATEGORY3LIST", []);
    try {
      const res = await categoryApi.getCategory2(category1Id);
      if (res.code === 200) {
        commit("UPDATE_CATEGORY2LIST", res.data);
        return "ok";
      } else {
        return Promise.reject("fail");
      }
    } catch (error) {
      Message({
        message: "获取二级分类列表失败",
        type: "error",
      });
    }
  },
  //获取三级分类列表
  async getCategory3List({ commit }, category2Id) {
    try {
      const res = await categoryApi.getCategory3(category2Id);
      if (res.code === 200) {
        commit("UPDATE_CATEGORY3LIST", res.data);
        return "ok";
      } else {
        return Promise.reject("fail");
      }
    } catch (error) {
      Message({
        message: "获取三级分类列表失败",
        type: "error",
      });
    }
  },
};
export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
